const Router = require('koa-router')
const logger = require('../utils/console-logger')

// 获取../controllers目录下的controller
const controllers = require('require-all')({
    dirname     :  require('path').resolve(__dirname, '../controllers'),
    filter      :  /(.+-controller)\.js$/,
    excludeDirs :  /^\.(git|svn)$/,
    recursive   : true
});

const api = new Router()

for (const controllerName in controllers) {
    logger.debug('加载路由: ', controllerName)
    const contoller = controllers[controllerName]
    const contollerRouter = new Router()
    for (const requestMappingKey in contoller) {
        if (requestMappingKey.indexOf('::') < 0) {
            logger.error(`  [!]路由方法映射名称错误。示例['get::/auth/doAuth']，你的['${requestMappingKey}']`)
            continue
        }
        const requestMapping = requestMappingKey.split('::')
        logger.debug('  路由方法映射: ',requestMapping)
        const requestType = requestMapping[0]
        const requestMethod = requestMapping[1]
        if (requestType && Reflect.has(contollerRouter,requestType)) {
            Reflect.apply(Reflect.get(contollerRouter,requestType), contollerRouter, [requestMethod, contoller[requestMappingKey]])
        } else {
            contollerRouter.all(requestMethod, contoller[requestMappingKey])
        }
    }
    api.use(contollerRouter.routes())
}

const router = new Router()
router.use('/api', api.routes())

module.exports = router
